<?php
/**
 * @Author: king
 * @Last Modified by:   king
 * Date: 2018/6/6
 * Time: 17:38
 */

namespace App\Models\Api;
use App\Exceptions\ApiException;
use App\Models\Api\Base;
use Illuminate\Database\Eloquent\Model;
use Cache;

class MapCollect extends Base
{
    protected $table = 'map_collect';

    public function map()
    {
      return  $this->hasOne('App\Models\Api\Map','id','mid','m');
    }
//TODO 占星地图收藏列表缓存
    /**
     * 获取收藏数据-- 根据rid
     */
    public function collect_rid($map=[])
    {
        $c_rid = $this->select('rid')->where('uid',$map['uid'])->orderBy('id','ASC')->distinct('rid')->get();
        $c_rid =json_decode(json_encode($c_rid,true),true);
        $rids =[];

        foreach ($c_rid as $k=>$v)
        {
            $rids[]=$v['rid'];
        }
        if (empty($map['rid'])) $map['rid'] = $rids[0];

        $where =['rid'=>$map['rid'],'uid'=>$map['uid']];

        $result=false;
        if (intval($this->cache_on)>=1)
        {
            Cache::get('map_collect_list_'.$map['rid']);
        }
        if ($result===false)
        {
            try {
                $result = $this
                    ->from('map_collect as mc')
                    ->select('mc.type','mc.id','mc.name','mc.des','m.longitude','m.latitude')
                    ->join('map as m', 'mc.mid','=','m.id', 'LEFT')
                    ->where($where)
                    ->orderBy('id','DESC')
                    ->paginate(10,false,['page'=>$map['page']]);

            } catch (\Exception $e) {
                $result=[
                    'rids'=>$rids,
                    'data'=>[]
                ];

            }
            $result = json_decode(json_encode($result,true),true);

            if (intval($this->cache_on)>=1)
               Cache::set('map_collect_list_'.$map['rid'],$result,86400*7);
        }

        $result['rids']= $rids;

        return $result;
    }

}
